/**
 * 
 */
package io.gitee.falllee.dao.core.table;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.util.CollectionUtils;

import io.gitee.falllee.common.page.PageRows;
import io.gitee.falllee.dao.enums.QueryModeEnum;
import io.gitee.falllee.dao.model.BaseDaoConfig;
import io.gitee.falllee.dao.util.DaoUtils;
import io.gitee.falllee.dao.util.FilterPlus;
import io.gitee.falllee.dao.util.SortPlus;

/**
 * @author batty
 * @date 2022-06-28
 *
 */
public class SelectFilterBuilder extends FilterBuilder {
    
    private SelectBuilder selectBuilder;
    
    private String sort;
    
    private Long page = 0L;
    
    private Long rows = 0L;
    
    private List<String> params;

    private QueryModeEnum queryMode = QueryModeEnum.DEFAULT;
    
    SelectFilterBuilder(SelectBuilder parent, BaseDaoConfig daoConfig, FilterPlus filterPlus) {
        super(daoConfig, filterPlus);
        this.selectBuilder = parent;
    }
    
    public SelectFilterBuilder sort(SortPlus sortPlus) {
        this.sort = sortPlus != null ? sortPlus.getSort() : null;
        return this;
    }
    
    public SelectFilterBuilder sort(String sort) {
        this.sort = sort;
        return this;
    }
    
    /**
     * page默认0，查询所有
     * 
     * @param page
     * @return
     */
    public SelectFilterBuilder page(Long page) {
        this.page = page;
        return this;
    }
    
    /**
     * rows默认0，查询所有
     * 
     * @param rows
     * @return
     */
    public SelectFilterBuilder rows(Long rows) {
        this.rows = rows;
        return this;
    }
    
    public SelectFilterBuilder addChildrenTable(String tableName) {
        if (params == null) {
            params = new ArrayList<>();
        }
        params.add(tableName);
        return this;
    }
    
    public SelectFilterBuilder queryMode(QueryModeEnum queryMode) {
        this.queryMode = queryMode;
        return this;
    }
    
    public List<Map<String, Object>> select() {
        String[] pars = DaoUtils.list2Array(params);
        return selectBuilder.select(filter, sort, page, rows, queryMode, pars);
    }
    
    public Map<String, Object> selectFirst() {
        String[] pars = DaoUtils.list2Array(params);
        List<Map<String, Object>> list = selectBuilder.select(filter, sort, 1L, 1L, QueryModeEnum.DEFAULT, pars);
        if (!CollectionUtils.isEmpty(list)) {
            return list.get(0);
        }
        return null;
    }
    
    public PageRows<Map<String, Object>> selectPage() {
        String[] pars = DaoUtils.list2Array(params);
        return selectBuilder.selectPage(filter, sort, page, rows, queryMode, pars);
    }
}
